package com.happy_lab_management.demo.teacher.experimentApplication.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.happy_lab_management.demo.admin.semester.service.SemesterService;
import com.happy_lab_management.demo.common.labType.service.LabTypeService;
import com.happy_lab_management.demo.common.section.service.SectionService;
import com.happy_lab_management.demo.common.weekday.service.WeekdayService;
import com.happy_lab_management.entity.*;
import com.happy_lab_management.entity.VO.ExperimentApplicationVO;
import com.happy_lab_management.result.Result;

import com.happy_lab_management.context.BaseContext;
import com.happy_lab_management.demo.admin.user.service.TeacherService;
import com.happy_lab_management.demo.teacher.experimentApplication.service.ExperimentApplicationService;
import com.happy_lab_management.entity.DTO.ExperimentApplicationDTO;
import com.happy_lab_management.util.CopyFieldUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RequestMapping("/teacher/experimentApplication")
@RestController("teacherExp")
public class ExperimentApplicationController {
    @Autowired
    private ExperimentApplicationService experimentApplicationService;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private LabTypeService labTypeService;
    @Autowired
    private SectionService sectionService;
    @Autowired
    private WeekdayService weekdayService;
    @Autowired
    private SemesterService semesterService;


    /*
    列出当前学期的自己的所有申请(申请状态有：已排课、未排课
*/

    /**
     * 测试
     */
    @PostMapping("/test")
    public Result<String> test() {
        experimentApplicationService.list();
        return Result.success("测试成功");
    }

    /**
     * 列出当前教师的所有申请
     *
     * @return
     */
    @RequestMapping("/list")
    public Result<IPage<ExperimentApplicationVO>> listExpApp(@RequestBody ExperimentApplication experimentApplicationGetter,
                                                             @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {

        //获取登录教师对应的申请记录
        Integer userId = BaseContext.getCurrentId();
        Teacher teacher = teacherService.selectByUserId(userId);

        QueryWrapper<ExperimentApplication> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("teacher_id", teacher.getId());

        if(experimentApplicationGetter.getSemesterId()!=null){
            queryWrapper.eq("semester_id", experimentApplicationGetter.getSemesterId());
        }
        if(experimentApplicationGetter.getCourseName()!=null){
            queryWrapper.like("course_name", experimentApplicationGetter.getCourseName());
        }
        if(experimentApplicationGetter.getLabType()!=null){
            queryWrapper.eq("lab_type", experimentApplicationGetter.getLabType());
        }
        if(experimentApplicationGetter.getClassname()!=null){
            queryWrapper.like("classname", experimentApplicationGetter.getClassname());
        }
        if(experimentApplicationGetter.getStudentCount()!=null){
            queryWrapper.eq("student_count", experimentApplicationGetter.getStudentCount());
        }
        if(experimentApplicationGetter.getStartWeek()!=null){
            queryWrapper.eq("start_week", experimentApplicationGetter.getStartWeek());
        }
        if(experimentApplicationGetter.getEndWeek()!=null){
            queryWrapper.eq("end_week", experimentApplicationGetter.getEndWeek());
        }
        if(experimentApplicationGetter.getWeekday()!=null){
            queryWrapper.eq("weekday", experimentApplicationGetter.getWeekday());
        }
        if(experimentApplicationGetter.getSection()!=null){
            queryWrapper.eq("section", experimentApplicationGetter.getSection());
        }
        if(experimentApplicationGetter.getStatus()!=null){
            queryWrapper.eq("status", experimentApplicationGetter.getStatus());
        }


        List<LabType> labTypeList = labTypeService.list();
        List<Section> sectionList = sectionService.list();
        List<Weekday> weekdayList = weekdayService.list();
        List<Semester> semesterList = semesterService.list();

        Map<Integer, String> labTypeMap = new HashMap<>();
        Map<Integer, String> sectionMap = new HashMap<>();
        Map<Integer, String> weekdayMap = new HashMap<>();
        Map<Integer, String> semesterMap = new HashMap<>();

        for (LabType labType : labTypeList) {
            labTypeMap.put(labType.getId(),labType.getLabTypeName());
        }
        for (Section section : sectionList) {
            sectionMap.put(section.getId(),section.getSectionName());
        }
        for (Weekday weekday : weekdayList) {
            weekdayMap.put(weekday.getId(),weekday.getWeekdayName());
        }
        for (Semester semester : semesterList) {
            semesterMap.put(semester.getId(),semester.getSemesterName());
        }

        //获取分页查询后的数据
        Page<ExperimentApplication> page = new Page<>(pageNo, pageSize);
        IPage<ExperimentApplication> pageList = experimentApplicationService.page(page, queryWrapper);
        List<ExperimentApplication> experimentApplications = pageList.getRecords();


        //使用VO类将id对应的名字也一起返回前端
        IPage<ExperimentApplicationVO> VOIPageList = new Page<>(pageList.getCurrent(), pageList.getSize());
        // 设置分页信息
        VOIPageList.setTotal(pageList.getTotal());
        VOIPageList.setPages(pageList.getPages());

        List<ExperimentApplicationVO> returnExperimentList = new ArrayList<>();
        int i = 0;
        for (ExperimentApplication experimentApplication : experimentApplications) {
            try {
                ExperimentApplicationVO returnObject = new ExperimentApplicationVO();
                CopyFieldUtil.copyCommonAttributes(experimentApplication, returnObject);
                //获取Section、Weekday、LabType的id对应的名字

                returnObject.setLabTypeName(labTypeMap.get(Integer.parseInt(experimentApplication.getLabType())));
                returnObject.setSectionName(sectionMap.get(experimentApplication.getSection()));
                returnObject.setWeekdayName(weekdayMap.get(experimentApplication.getWeekday()));
                returnObject.setSemesterName(semesterMap.get(experimentApplication.getSemesterId()));
                returnExperimentList.add(returnObject);
                i++;
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        VOIPageList.setRecords(returnExperimentList);
        return Result.success(VOIPageList);
    }

    /**
     * 教师填写实验室申请
     *
     * @param experimentApplicationDTO
     * @return
     */
    @RequestMapping("/add")
    public Result<String> add(@RequestBody ExperimentApplicationDTO experimentApplicationDTO) {
        if (experimentApplicationDTO.getSection() == null || experimentApplicationDTO.getWeekday() == null
                || experimentApplicationDTO.getClassname() == null || experimentApplicationDTO.getLabType() == null
                || experimentApplicationDTO.getCourseName() == null || experimentApplicationDTO.getStudentCount() == null
                || experimentApplicationDTO.getSemesterId() == null || experimentApplicationDTO.getStartWeek() == null
                || experimentApplicationDTO.getEndWeek() == null) {
            return Result.error("缺少必须的数据项");
        }

        ExperimentApplication experimentApplication = new ExperimentApplication();
        BeanUtils.copyProperties(experimentApplicationDTO, experimentApplication);
        //获取用户id，再查询教师id
        Integer userId = BaseContext.getCurrentId();
        Teacher teacher = teacherService.selectByUserId(userId);
        experimentApplication.setTeacherId(teacher.getId());
        experimentApplication.setStatus("未排课");
        experimentApplicationService.save(experimentApplication);
        return Result.success("填写成功");
    }

    @PostMapping("/edit")
    public Result<String> edit(@RequestBody ExperimentApplication experimentApplication) {
        if (experimentApplication.getStatus().equals("已排课")) {
            return Result.error("已排课，无法修改");
        }
        experimentApplicationService.updateById(experimentApplication);

        return Result.success("修改成功");

    }

    /*
    删除单条数据
     */
    @PostMapping("/delete")
    public Result<String> delete(@RequestBody ExperimentApplication experimentApplication) {
        try{
            experimentApplicationService.removeById(experimentApplication.getId());
            return Result.success("删除成功");
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("删除失败");
        }
    }

    /*
        批量删除数据
     */
    @PostMapping("/deleteList")
    public Result<String> deleteList(@RequestBody List<Integer> ids) {
        try{
            for (Integer id : ids) {
                experimentApplicationService.removeById(id);
            }
            return Result.success("删除成功");
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("删除失败");
        }


    }

}
